<template>
  <a-cascader
    :options="bizTypeData"
    :show-search="isLazy ? false : { bizTypeFilter }"
    :load-data="loadData"
    :fieldNames="{ label: 'name', value: 'id', children: 'children' }"
    @change="onBizChange"
    :placeholder="placeholder"
    :changeOnSelect="true"
    v-model="selectedBizType"
  >
    <a-icon slot="suffixIcon" type="" />
  </a-cascader>
</template>

<script>
import { findByBizType, findProcessNodeList } from '@/api/std/std_matter.js'
import { queryStd_categoryList } from '@/api/std/std_category.js'
import { queryStd_biztypeList } from '@/api/std/std_biztype.js'
import { queryStd_matterList } from '@/api/std/std_matter.js'
import { tree } from '@/api/std/std_biztype'

export default {
  props: {
    // 描述
    placeholder: {
      type: String,
      default: '请选择',
    },
    // 是否懒加载
    isLazy: {
      type: Boolean,
      default: false,
    },
    // 回显值列表
    echoList: {
      type: Array,
      default: () => [],
    },
    // 是否需要显示环节
    showStep: {
      type: Boolean,
      default: true,
    },
    isAddAll: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      selectedBizType: [], // 级联选择器回显列表
      bizTypeData: [], // 树组件数据
    }
  },
  created() {
    // 如果需要回显, 在回显哪里进行初始化, 确保数据能出来
    console.log('this.echoList', this.echoList, this.echoList.length > 0)
    if (this.echoList.length == 0) {
      if (this.isLazy) {
        this.findBizTypeList()
      } else {
        tree().then((res) => {
          if (res.code === 0 && res.data) {
            this.bizTypeData = this.fixChildren(res.data) || []
            // console.log('下拉级联数据', this.bizTypeData)
          }
        })
      }
    } else {
      // console.log('开始回显1', val)
      this.findEchoList(this.echoList)
    }
  },
  watch: {
    async echoList(val) {
      this.findEchoList(val)
    },
  },
  methods: {
    // 查询回显值
    async findEchoList(val) {
      console.log('开始回显2', val)
      if (this.bizTypeData.length == 0) {
        await this.findBizTypeList()
      }
      this.selectedBizType = val
      for (let i = 0; i <= this.bizTypeData.length - 1; i++) {
        if (this.bizTypeData[i].id == val[0]) {
          let res = await queryStd_biztypeList({
            pageSize: 2147483647,
            f_cateid: this.bizTypeData[i].id == 'all' ? null : this.bizTypeData[i].id,
          })
          if (res.code == 0) {
            res.data.records = res.data.records || []
            if (this.isAddAll) {
              res.data.records.unshift({
                id: 'all',
                name: '全部业务',
                isLeaf: false,
              })
            }
            res.data.records &&
              res.data.records.map((v) => {
                v.isLeaf = false
                return v
              })
            this.bizTypeData[i].children = res.data.records || []
            for (let j = 0; j <= this.bizTypeData[i].children.length - 1; j++) {
              if (this.bizTypeData[i].children[j].id == val[1]) {
                // console.log('回显查询环节')
                let resn = null
                if (this.showStep) {
                  resn = await findProcessNodeList(
                    this.bizTypeData[i].children[j].id == 'all' ? null : this.bizTypeData[i].children[j].id
                  )
                } else {
                  resn = await queryStd_matterList({
                    pageSize: 2147483647,
                    f_bizid: this.bizTypeData[i].children[j].id == 'all' ? null : this.bizTypeData[i].children[j].id,
                  })
                }
                if (resn.code == 0) {
                  resn.data = resn.data.records || resn.data || []
                  resn.data.unshift({
                    id: 'all',
                    name: this.showStep ? '全部环节' : '全部事项',
                  })
                  this.bizTypeData[i].children[j].children = resn.data || []
                  this.bizTypeData = [...this.bizTypeData]
                }
                break
              }
            }
            this.bizTypeData = [...this.bizTypeData]
          }
          break
        }
      }
    },
    async findBizTypeList() {
      await queryStd_categoryList({ pageSize: 2147483647 }).then((res) => {
        console.log('下拉级联数据', res)
        if (res.code == 0) {
          this.bizTypeData = this.fixChildren(res.data) || []
          if (this.isAddAll) {
            this.bizTypeData.unshift({
              id: 'all',
              name: '全部分类',
              isLeaf: false,
            })
          }
        }
      })
    },
    // 关闭清空数据调用
    f_close() {
      this.selectedBizType = []
    },
    // 懒加载
    async loadData(selectedOptions) {
      console.log('懒加载', selectedOptions)
      const cateid = selectedOptions[0]?.id || null
      const applyid = selectedOptions[1]?.id || null

      const targetOption = selectedOptions[selectedOptions.length - 1]
      targetOption.loading = true

      // 根据长度判断该调那个接口
      let list = await this.getLazyList(
        selectedOptions.length,
        applyid == 'all' ? null : applyid,
        cateid == 'all' ? null : cateid
      )
      // console.log('懒列表', list)
      targetOption.children = list
      targetOption.loading = false
      this.bizTypeData = [...this.bizTypeData]
    },
    // 懒加载数据
    async getLazyList(sign, applyid, cateid) {
      let list = []
      if (sign == 1) {
        let res = await queryStd_biztypeList({ pageSize: 2147483647, f_cateid: cateid })
        console.log('分类列表', res)
        if (res.code == 0) {
          res.data.records = res.data.records || []
          if (this.isAddAll) {
            res.data.records.unshift({
              id: 'all',
              name: '全部业务',
              isLeaf: false,
            })
          }
          list = res.data.records || []
        }
      } else if (sign == 2 && this.showStep) {
        let res = await findProcessNodeList(applyid)
        console.log('环节列表', res)
        if (res.code == 0) {
          res.data = res.data || []
          if (this.isAddAll) {
            res.data.unshift({
              id: 'all',
              name: '全部环节',
            })
          }
          list = res.data || []
        }
      } else if (sign == 2 && this.showStep == false) {
        let res = await queryStd_matterList({ pageSize: 2147483647, f_bizid: applyid })
        console.log('事项列表', res)
        if (res.code == 0) {
          res.data = res.data.records || []
          if (this.isAddAll) {
            res.data.unshift({
              id: 'all',
              name: '全部事项',
            })
          }
          list = res.data || []
        }
      } else {
        console.error('未知的懒加载节点', sign)
        return null
      }
      list = list.map((v) => {
        v.isLeaf = sign == 2 ? true : false
        return v
      })
      return list
    },
    // 级联触发事件
    onBizChange(value, selectedOptions) {
      this.selectedBizType = value || []
      this.$emit('f_onBizChange', value)
      // 查询异步查询分类下的事项列表
      if (this.isLazy == false) {
        const cateId = value[0]
        const applyid = value[1]
        findByBizType({ bizId: applyid, cateId: cateId }).then((res) => {
          if (res.code === 0) {
            this.$emit('f_onMatChange', res.data || [])
          }
        })
      }
    },
    // 搜索条件过滤
    bizTypeFilter(inputValue, path) {
      return path.some((option) => option.label.indexOf(inputValue) > -1)
    },
    // 树空的子节点过滤掉
    fixChildren(data) {
      return data.map((item) => {
        if (!item.children || item.children.length === 0) {
          if (this.isLazy) {
            item.isLeaf = false
          }
          delete item.children
        } else {
          item.children = this.fixChildren(item.children)
        }
        return item
      })
    },
  },
}
</script>

<style lang="less" scoped>
</style>
